<template>
  <div class="person-warp">
    <a-row>
      <a-col :span="5">
        <div class="person-tree-warp">
          <!-- <div class="tree-search">
            <a-input-search
              v-model="state.treeSearch"
              placeholder="请输入部门名称"
              allow-clear
              search-button
              @search="onTreeSearch"
              @clear="onTreeSearchClear"
            />
          </div> -->
          <div class="top-actions">
            <span title="新增顶级部门"><IconPlus @click="onAddDep('')" /></span>
          </div>
          <a-tree
            :class="['scrollbar']"
            style="overflow-y: auto; height: calc(100% - 20px)"
            :blockNode="true"
            :checkable="true"
            :data="state.treeData"
            @check="onTreeSelect"
            check-strictly
          >
            <template #extra="nodeData">
              <!-- 新增部门 -->
              <span title="新增部门">
                <IconPlus
                  style="font-size: 14px; color: #3370ff; margin-right: 8px"
                  @click="onAddDep(nodeData)"
                />
              </span>
              <!-- 编辑部门 -->
              <span title="编辑部门">
                <icon-edit
                  style="font-size: 14px; color: #3370ff; margin-right: 8px"
                  @click="onEditDep(nodeData)"
                />
              </span>
              <!-- 删除部门 -->
              <a-popconfirm
                :content="`是否确认删除 部门名称：${state.currentTreeNode?.title} 吗?`"
                type="warning"
                @ok="delDep"
              >
                <icon-delete
                  style="font-size: 14px; color: #3370ff"
                  @click="onDelDep(nodeData)"
                />
              </a-popconfirm>
            </template>
          </a-tree>
        </div>
      </a-col>
      <a-col :span="19">
        <div class="person-table-warp">
          <div class="table-search">
            <a-form :model="state.tableForm">
              <a-row>
                <a-col :span="7">
                  <a-form-item field="code" label="工号">
                    <a-input
                      v-model="state.tableForm.code"
                      placeholder="请输入工号"
                    /> </a-form-item
                ></a-col>
                <a-col :span="7">
                  <a-form-item field="name" label="姓名">
                    <a-input
                      v-model="state.tableForm.name"
                      placeholder="请输入姓名"
                    /> </a-form-item
                ></a-col>
                <a-col :span="7">
                  <a-form-item field="positionCode" label="职位">
                    <a-select
                      placeholder="请选择职位"
                      v-model="state.tableForm.positionCode"
                    >
                      <a-option
                        v-for="item in state.positionList"
                        :value="item?.value"
                        >{{ item?.label }}</a-option
                      >
                    </a-select>
                  </a-form-item></a-col
                >
                <a-col :span="3">
                  <a-form-item style="justify-content: flex-end">
                    <a-button @click="handleReset"> 重置 </a-button>
                    <a-button
                      @click="handleSearch"
                      style="margin-left: 5px"
                      type="primary"
                    >
                      查询
                    </a-button>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <div class="table-actions">
            <a-button
              type="outline"
              status="danger"
              v-if="selectedKeys.length > 0"
              @click="handleDelete"
              >删除</a-button
            >
            <a-button
              type="primary"
              @click="handleCreate"
              style="margin-left: 5px"
              >新增</a-button
            >
          </div>
          <a-table
            row-key="code"
            :columns="columns"
            :data="state.tableData"
            :row-selection="rowSelection"
            v-model:selectedKeys="selectedKeys"
            :pagination="false"
          >
            <template #optional="{ record }">
              <a-button @click="handleUpdate(record)">编辑</a-button>
            </template>
          </a-table>
          <div class="pagetion">
            <a-pagination
              :total="state.tableTotal"
              :page-size="state.pageInfo.pageSize"
              @change="pageChange"
              @page-size-change="pageSzChange"
              show-page-size
            />
          </div>
        </div>
      </a-col>
    </a-row>

    <a-modal
      v-model:visible="state.treeModelVisible"
      @ok="handleModel"
      :unmount-on-close="true"
      @cancel="() => (state.treeModelVisible = false)"
    >
      <template #title>
        {{ state.treeModelType === "add" ? "新增" : "编辑" }}
      </template>
      <a-form :model="state.treeForm" auto-label-width>
        <a-form-item field="name" label="部门名称">
          <a-input v-model="state.treeForm.name" />
        </a-form-item>
      </a-form>
    </a-modal>

    <EditForm ref="editFormRef" @refresh="getTableData()"></EditForm>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import { formatTree } from "@/utils/tree";
import EditForm from "./editForm.vue";
import Modal from "@arco-design/web-vue/es/modal";
import {
  useEmployeeDeleteApi,
  useEmployeePageApi,
  useOrganizationCreateApi,
  useOrganizationDeleteApi,
  useOrganizationListApi,
  useOrganizationUpdateApi,
  usePositionDeleteApi,
  usePositionListApi,
  usePositionPageApi,
} from "@/api";
import { Message } from "@arco-design/web-vue";
const editFormRef = ref();

// 树形Form
const useTreeForm = () => {
  return {
    name: "",
  };
};
// 表格Form
const useTableForm = () => {
  return {
    code: "",
    name: "",
    positionCode: "",
  };
};
const state = reactive({
  tableForm: useTableForm(),
  treeForm: useTreeForm(),
  tableTotal: 0,
  tableData: [],
  pageInfo: {
    pageNum: 1,
    pageSize: 10,
  },
  organizationCode: [],
  currentTreeNode: null, //当前树形选中节点
  treeModelVisible: false, //控制树形弹窗
  treeData: [], //树形数据
  treeSearch: "", //控制树形弹窗
  treeModelType: "add", //树形弹窗类型
  modelVisible: false, //控制表单弹窗
  deleteModelVisible: false, //控制删除弹窗
  positionList: [], //职位数据
});

onMounted(() => {
  getTableData();
  getTreeData();
  getPositionList();
});

const getPositionList = () => {
  usePositionListApi({}).then(({ data }) => {
    state.positionList = data?.map((item) => {
      return {
        ...item,
        label: item.name,
        value: item.code,
      };
    });
  }) || [];
};
const pageChange = (c) => {
  state.pageInfo.pageNum = c;
};
const pageSzChange = (p) => {
  state.pageInfo.pageSize = p;
};

const getTreeData = () => {
  useOrganizationListApi({}).then(({ data }) => {
    data = data?.map((item) => {
      return {
        ...item,
        key: item.code,
        title: item.name,
      };
    });
    let tree = formatTree(data, "");
    state.treeData = tree;
  });
};

//树形结构搜索
const onTreeSearch = () => {
  console.log("onTreeSearch", state.treeSearch);
};
//树形结构搜索
const onTreeSearchClear = () => {
  console.log("onTreeSearch", state.treeSearch);
};

// 新增部门
const onAddDep = (nodeData: any) => {
  state.treeModelType = "add";
  state.treeModelVisible = true;
  state.currentTreeNode = nodeData;
};
// 编辑部门
const onEditDep = (nodeData: any) => {
  state.currentTreeNode = nodeData;
  state.treeModelType = "edit";
  state.treeModelVisible = true;
  state.treeForm.name = nodeData.title;
};

const handleModel = () => {
  if (state.treeModelType === "add") {
    if (state.currentTreeNode !== "") {
      useOrganizationCreateApi(
        Object.assign({}, state.treeForm, {
          parentCode: state.currentTreeNode.code,
        })
      ).then(() => {
        getTreeData();
        state.treeForm = useTreeForm();
      });
      return;
    }
    useOrganizationCreateApi(
      Object.assign({}, state.treeForm, { parentCode: "" })
    ).then(() => {
      getTreeData();
      state.treeForm = useTreeForm();
    });
  } else {
    useOrganizationUpdateApi(
      Object.assign({}, state.treeForm, { code: state.currentTreeNode.code })
    ).then(() => {
      getTreeData();
      state.treeForm = useTreeForm();
    });
  }
};
// 删除部门
const onDelDep = (nodeData: any) => {
  state.currentTreeNode = nodeData;
};
// 确认删除部门
const delDep = () => {
  console.log(state.currentTreeNode?.title);
  useOrganizationDeleteApi({ codeList: [state.currentTreeNode.code] }).then(
    () => {
      getTreeData();
    }
  );
};

// 表格搜索重置
const handleReset = () => {
  state.tableForm = useTableForm();
  state.pageInfo.pageNum = 1;
  state.pageInfo.pageSize = 10;
  getTableData();
};
// 表格搜索查询
const handleSearch = () => {
  getTableData();
};

//获取表格数据
const getTableData = () => {
  useEmployeePageApi(
    Object.assign({}, state.pageInfo, state.tableForm, {
      orgCodeList: state.organizationCode,
    })
  ).then(({ data: { list, total } }) => {
    state.tableTotal = total;
    state.tableData = list;
  });
};

const onTreeSelect = (selectedKeys, data) => {
  console.log(selectedKeys, data, "selectedKeys,data");
  state.organizationCode = selectedKeys;
  getTableData();
};

const handleCreate = () => {
  editFormRef.value.open("create");
};
const handleUpdate = (row: any) => {
  editFormRef.value.open("update", row);
};
const handleDelete = () => {
  console.log(selectedKeys.value);
  Modal.warning({
    title: "删除",
    content: "是否确认删除选中的数据？",
    modalStyle: { textAlign: "center", fontSize: "16px" },
    bodyStyle: { fontSize: "14px" },
    cancelText: "取消",
    width: 300,
    closable: true,
    onOk: () => {
      useEmployeeDeleteApi({ codeList: selectedKeys.value })
        .then(() => {
          Message.success("操作成功");
        })
        .catch(() => Message.error("操作失败"))
        .finally(() => {
          selectedKeys.value = [];
          getTableData();
        });
    },
  });
};

const rowSelection = reactive({
  type: "checkbox",
  showCheckedAll: false,
  onlyCurrent: false,
});

const selectedKeys = ref([]);
const columns = [
  {
    title: "学号",
    dataIndex: "code",
  },
  {
    title: "姓名",
    dataIndex: "name",
  },
  {
    title: "部门",
    dataIndex: "organizationName",
  },
  {
    title: "职位",
    dataIndex: "positionName",
  },
  {
    title: "操作",
    slotName: "optional",
  },
];
</script>

<style scoped lang="less">
.person-warp {
  .person-tree-warp {
    border-right: 1px solid #e8e8e8;
    height: calc(100vh - 110px);
    overflow-y: hidden;
    padding: 10px;

    .tree-search {
      height: 52px;
    }
    .top-actions {
      display: flex;
      justify-content: flex-end;
      cursor: pointer;
    }
  }
  .person-table-warp {
    padding: 10px;

    .table-search {
      :deep(.arco-form-item) {
        margin-bottom: 0 !important;
      }
      :deep(.arco-form-item-content-flex) {
        justify-content: flex-end !important;
      }
      margin-bottom: 5px;
    }
    .table-actions {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 5px;
    }
  }
  .pagetion {
    margin-top: 10px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
